<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>

</head>
<body>
<h1>Hello, WebSocket</h1>
<p>
    <input type="text" width="10%" id="message" /> &nbsp;&nbsp; &nbsp;
    <button type="button" name="Send" value="Send" onclick="sendMessage()">Send</button>
</p>

<p>
    <h3>Message Box：</h3>
    <textarea id="messageBox" rows="50" cols="200"></textarea>
</p>

</body>
<script src="/static/jquery-3.3.1.js"></script>

<script th:inline="javascript">
function getSid(){
    var url = location.href;
    var temp2 = url.split('?')[1];
    var params = new URLSearchParams('?'+temp2);
    var sid = params.get("sid");
    console.info("sid=" + sid);
    return sid;
}

function getType(){
    var url = location.href;
    var temp2 = url.split('?')[1];
    var params = new URLSearchParams('?'+temp2);
    var type = params.get("type");
    console.info("type=" + type);
    return type;
}

function sendMessage(){
    var message = document.getElementById("message");
    var messageBox = document.getElementById("messageBox");

    var msgText = message.value;
    messageBox.value = messageBox.value + "Send：" + msgText + "\n";

    var url = "http://localhost:9001/websocket/push/" + getSid() + "?message=" + msgText;
    $.get(url, function(data,status){
        message.value = "";
    });
}

function showMessage(message){
    var messageBox = document.getElementById("messageBox");
    messageBox.value = messageBox.value + new Date().Format("yyyy-MM-dd hh:mm:ss.S") + " Receive：" + message + "\n";
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")   ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };

    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

    return fmt;
}
</script>

<script th:inline="javascript">
var socket;

var heartCheck = {
    timeout: 10000, //10m
    timeoutObj: null,
    reset: function(){
        clearTimeout(this.timeoutObj);
        this.start();
    },
    start: function(){
        this.timeoutObj = setTimeout(function(){
            var ping = "Ping " + getType();
            showMessage("Send：" + ping);
            socket.send(ping);
        }, this.timeout)
    }
}


function reconnect(){
    socket = new WebSocket("ws://localhost:9001/websocket/" + getSid());
}

if(typeof(WebSocket) == "undefined") {
    showMessage("您的浏览器不支持WebSocket");
}else{
    console.log("您的浏览器支持WebSocket");

    socket = new WebSocket("ws://localhost:9001/websocket/" + getSid());

    //打开事件
    socket.onopen = function() {
        showMessage("Socket 已打开");
        socket.send("这是来自客户端的消息" + location.href + new Date());
        heartCheck.start();
    };

    //获得消息事件
    socket.onmessage = function(msg) {
        //发现消息进入开始处理前端触发逻辑
        showMessage(msg.data);
        heartCheck.reset();
    };

    //关闭事件
    socket.onclose = function() {
        showMessage("Socket已关闭");
        reconnect();
    };

    //发生了错误事件
    socket.onerror = function() {
        showMessage("Socket发生了错误");
        //此时可以尝试刷新页面
        reconnect();
    }
}
</script>
</html>